<template>
  <!-- 数字人主动播报与智能推送中心 -->
  <div class="digital-human-container glass-card p-6 relative overflow-hidden">
    <!-- 背景装饰 -->
    <div class="absolute top-0 right-0 w-32 h-32 bg-gradient-to-bl from-red-500/20 to-transparent rounded-full blur-xl"
      v-if="isAnnouncing"></div>
    <div
      class="absolute top-0 right-0 w-32 h-32 bg-gradient-to-bl from-electric-500/20 to-transparent rounded-full blur-xl"
      v-else></div>
    <div
      class="absolute bottom-0 left-0 w-24 h-24 bg-gradient-to-tr from-tech-blue-500/20 to-transparent rounded-full blur-xl">
    </div>

    <div class="relative z-10">
      <!-- 标题区域 -->
      <div class="flex items-center justify-between mb-6">
        <div class="flex items-center space-x-3">
          <div class="p-2 bg-gradient-to-r from-electric-500/20 to-tech-blue-500/20 rounded-lg">
            <Bot class="w-6 h-6 text-electric-500" />
          </div>
          <div>
            <h3 class="text-lg font-semibold text-white">{{ ts('AI数字人主动播报') }}</h3>
            <p class="text-sm text-gray-400">{{ ts('智能政策推送·主动播报·实时分析') }}</p>
          </div>
        </div>
        <div class="flex items-center space-x-3">
          <div class="flex items-center space-x-2">
            <div :class="[
              'w-2 h-2 rounded-full',
              isAnnouncing ? 'bg-red-400 animate-pulse' :
                agentActive ? 'bg-green-400 animate-pulse' : 'bg-gray-400'
            ]"></div>
            <span :class="[
              'text-xs font-medium',
              isAnnouncing ? 'text-red-400' :
                agentActive ? 'text-green-400' : 'text-gray-400'
            ]">
              {{ currentStatusText }}
            </span>
          </div>
          <button @click="openBroadcastSettings"
            class="px-2 py-1 bg-electric-500/20 text-electric-500 rounded text-xs hover:bg-electric-500/30 transition-colors">
            {{ ts('播报设置') }}
          </button>
        </div>
      </div>

      <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <!-- AI数字人播报区域 -->
        <div class="space-y-4">
          <!-- 数字人头像容器 -->
          <div class="digital-human-avatar relative w-full h-64 rounded-xl overflow-hidden border-2"
            :class="avatarBorderClass">
            <!-- 数字人视频播放 -->
            <video ref="digitalHumanVideo" src="/视频.mp4"
              class="absolute inset-0 w-full h-full object-cover transition-all duration-300"
              :class="{ 'animate-pulse scale-105': isSpeaking || isAnnouncing }" autoplay loop muted playsinline />

            <!-- 悬浮遮罩层 -->
            <div class="absolute inset-0 bg-gradient-to-t from-black/50 via-transparent to-transparent"></div>

            <!-- 播报时的特效动画 -->
            <div v-if="isAnnouncing" class="absolute inset-0 z-10">
              <div class="absolute inset-0 border-2 border-red-500/60 animate-ping rounded-xl"></div>
              <div class="absolute inset-2 border-2 border-yellow-500/60 animate-ping animation-delay-200 rounded-lg">
              </div>
              <div class="absolute inset-4 border-2 border-electric-500/60 animate-ping animation-delay-400 rounded-md">
              </div>
              <!-- 紧急播报标识 -->
              <div
                class="absolute top-4 left-4 bg-red-500/90 text-white px-2 py-1 rounded text-xs font-bold animate-pulse">
                {{ ts('紧急播报') }}
              </div>
            </div>

            <!-- 正常说话时的波纹效果 -->
            <div v-else-if="isSpeaking" class="absolute inset-0 z-10">
              <div class="absolute inset-0 border-2 border-electric-500/50 animate-ping rounded-xl"></div>
              <div
                class="absolute inset-2 border-2 border-tech-blue-500/50 animate-ping animation-delay-200 rounded-lg">
              </div>
              <div class="absolute inset-4 border-2 border-yellow-400/50 animate-ping animation-delay-400 rounded-md">
              </div>
            </div>

            <!-- 状态指示器 -->
            <div
              class="absolute bottom-4 left-4 flex items-center space-x-2 bg-black/70 backdrop-blur-sm rounded-lg px-3 py-2">
              <div :class="[
                'w-2 h-2 rounded-full',
                isAnnouncing ? 'bg-red-400 animate-pulse' :
                  isSpeaking ? 'bg-yellow-400 animate-pulse' : 'bg-green-400'
              ]"></div>
              <span :class="[
                'text-xs font-medium',
                isAnnouncing ? 'text-red-400' :
                  isSpeaking ? 'text-yellow-400' : 'text-green-400'
              ]">
                {{ currentStatus }}
              </span>
            </div>

            <!-- 音频可视化 -->
            <div
              class="absolute bottom-4 right-4 flex items-center space-x-1 bg-black/70 backdrop-blur-sm rounded-lg px-3 py-2">
              <div v-for="i in 5" :key="i" class="w-1 rounded-full transition-all duration-300"
                :class="audioVisualizerClass" :style="{
                  height: (isSpeaking || isAnnouncing) ? `${Math.random() * 16 + 8}px` : '4px',
                  animationDelay: `${i * 0.1}s`
                }"></div>
            </div>

            <!-- 播报进度条 -->
            <div v-if="isAnnouncing && currentAnnouncement" class="absolute bottom-0 left-0 right-0 h-1 bg-black/50">
              <div class="h-full bg-red-500 transition-all duration-100" :style="{ width: `${announcementProgress}%` }">
              </div>
            </div>
          </div>

          <!-- 当前播报内容显示 -->
          <div v-if="currentAnnouncement" class="announcement-display">
            <div class="bg-red-900/30 border border-red-500/30 rounded-lg p-4 mb-3">
              <div class="flex items-center space-x-2 mb-2">
                <Volume2 class="w-4 h-4 text-red-400 animate-pulse" />
                <span class="text-red-400 text-sm font-medium">{{ ts('正在播报') }}</span>
                <span class="text-xs text-red-300 bg-red-500/20 px-2 py-1 rounded">
                  {{ getUrgencyText(currentAnnouncement.urgency) }}
                </span>
              </div>
              <!-- 打字机效果的文本显示 -->
              <div class="text-white/90 text-sm leading-relaxed">
                <span class="typewriter-text">{{ displayedText }}</span>
                <span v-if="isTyping" class="animate-pulse">|</span>
              </div>
              <div class="flex items-center justify-between mt-3 text-xs">
                <span class="text-gray-400">{{ ts('播报时长') }}: {{ formatDuration(currentAnnouncement.duration) }}</span>
                <span class="text-gray-400">{{ formatTime(currentAnnouncement.timestamp) }}</span>
              </div>
            </div>
          </div>

          <!-- 操作控制按钮 -->
          <div class="grid grid-cols-4 gap-2">
            <button @click="triggerManualBroadcast" :disabled="isAnnouncing"
              class="px-3 py-2 bg-yellow-500/20 text-yellow-400 rounded-lg hover:bg-yellow-500/30 transition-colors flex items-center justify-center space-x-1 disabled:opacity-50">
              <Radio class="w-4 h-4" />
              <span class="text-xs">{{ ts('手动播报') }}</span>
            </button>
            <button @click="pauseOrResumeAnnouncement" v-if="isAnnouncing"
              class="px-3 py-2 bg-blue-500/20 text-blue-400 rounded-lg hover:bg-blue-500/30 transition-colors flex items-center justify-center space-x-1">
              <component :is="isPaused ? 'Play' : 'Pause'" class="w-4 h-4" />
              <span class="text-xs">{{ isPaused ? ts('继续') : ts('暂停') }}</span>
            </button>
            <button @click="stopCurrentAnnouncement" v-if="isAnnouncing"
              class="px-3 py-2 bg-red-500/20 text-red-400 rounded-lg hover:bg-red-500/30 transition-colors flex items-center justify-center space-x-1">
              <Square class="w-4 h-4" />
              <span class="text-xs">{{ ts('停止') }}</span>
            </button>
            <button @click="openBroadcastSettings"
              class="px-3 py-2 bg-tech-blue-500/20 text-tech-blue-400 rounded-lg hover:bg-tech-blue-500/30 transition-colors flex items-center justify-center space-x-1">
              <Settings class="w-4 h-4" />
              <span class="text-xs">{{ ts('设置') }}</span>
            </button>
          </div>
        </div>

        <!-- 智能推送与企业政策区域 -->
        <div class="space-y-4">
          <!-- 今日重点推送 -->
          <div class="bg-gray-800/30 rounded-lg p-4 border" :style="{
            backgroundColor: 'var(--color-surface)',
            border: '1px solid var(--color-border)'
          }">
            <div class="flex items-center justify-between mb-3">
              <h4 class="text-white font-medium flex items-center">
                <Target class="w-4 h-4 mr-2 text-yellow-400" />
                {{ ts('今日重点推送') }}
              </h4>
              <div class="flex items-center space-x-2">
                <span class="text-xs text-yellow-400 bg-yellow-400/20 px-2 py-1 rounded">
                  {{ todayHighlights.length }}{{ ts('条') }}
                </span>
                <button @click="refreshHighlights" class="text-yellow-400 hover:text-yellow-300 transition-colors">
                  <RefreshCw class="w-3 h-3" />
                </button>
              </div>
            </div>
            <div class="space-y-2 max-h-40 overflow-y-auto custom-scrollbar">
              <div v-for="highlight in todayHighlights" :key="highlight.id"
                class="p-3 rounded bg-white/5 hover:bg-white/10 transition-colors cursor-pointer border-l-2"
                :class="getHighlightBorderClass(highlight.urgency)" @click="announceHighlight(highlight)">
                <div class="flex items-center justify-between mb-2">
                  <span class="text-white text-xs font-medium truncate flex-1 mr-2">{{ highlight.title }}</span>
                  <span :class="getUrgencyBadgeClass(highlight.urgency)"
                    class="text-xs px-2 py-1 rounded flex-shrink-0">
                    {{ getUrgencyText(highlight.urgency) }}
                  </span>
                </div>
                <p class="text-gray-400 text-xs line-clamp-2 mb-2">{{ highlight.summary }}</p>
                <div class="flex items-center justify-between text-xs">
                  <span class="text-electric-500">{{ highlight.matchScore ? `${Math.round(highlight.matchScore *
                    100)}%匹配` : '' }}</span>
                  <span class="text-gray-500">{{ formatTime(highlight.timestamp) }}</span>
                </div>
              </div>

              <div v-if="todayHighlights.length === 0" class="text-center text-white/50 text-sm py-6">
                <Target class="w-8 h-8 mx-auto mb-2 opacity-50" />
                <p>{{ ts('暂无重点推送') }}</p>
                <p class="text-xs mt-1">{{ ts('智能Agent将实时为您推送相关政策') }}</p>
              </div>
            </div>
          </div>

          <!-- 企业定制政策展示 -->
          <div class="bg-gray-800/30 rounded-lg p-4 border" :style="{
            backgroundColor: 'var(--color-surface)',
            border: '1px solid var(--color-border)'
          }">
            <div class="flex items-center justify-between mb-3">
              <h4 class="text-white font-medium flex items-center">
                <Building class="w-4 h-4 mr-2 text-tech-blue-400" />
                {{ ts('企业定制政策') }}
              </h4>
              <div class="flex items-center space-x-2">
                <span class="text-xs text-tech-blue-400 bg-tech-blue-400/20 px-2 py-1 rounded">
                  {{ customPolicies.length }}{{ ts('项') }}
                </span>
                <button @click="refreshCustomPolicies"
                  class="text-tech-blue-400 hover:text-tech-blue-300 transition-colors">
                  <RefreshCw class="w-3 h-3" />
                </button>
              </div>
            </div>
            <div class="space-y-2 max-h-40 overflow-y-auto custom-scrollbar">
              <div v-for="policy in customPolicies" :key="policy.id"
                class="p-3 rounded bg-white/5 hover:bg-white/10 transition-colors cursor-pointer"
                @click="announcePolicyDetails(policy)">
                <div class="flex items-center justify-between mb-2">
                  <span class="text-white text-xs font-medium truncate flex-1 mr-2">{{ policy.title }}</span>
                  <div class="flex items-center space-x-1">
                    <span class="text-xs text-green-400 bg-green-400/20 px-2 py-1 rounded">
                      {{ Math.round((policy.matchScore || 0.8) * 100) }}%
                    </span>
                    <button @click.stop="announcePolicyDetails(policy)"
                      class="text-yellow-400 hover:text-yellow-300 p-1">
                      <Volume2 class="w-3 h-3" />
                    </button>
                  </div>
                </div>
                <p class="text-gray-400 text-xs line-clamp-2 mb-2">{{ policy.description }}</p>
                <div class="flex items-center justify-between text-xs">
                  <span class="text-electric-500 font-medium">{{ policy.benefit }}</span>
                  <span class="text-gray-500">{{ policy.region }}</span>
                </div>
              </div>

              <div v-if="customPolicies.length === 0" class="text-center text-white/50 text-sm py-6">
                <Building class="w-8 h-8 mx-auto mb-2 opacity-50" />
                <p>{{ ts('暂无定制政策') }}</p>
                <p class="text-xs mt-1">{{ ts('系统正在为您分析匹配政策...') }}</p>
              </div>
            </div>
          </div>

          <!-- 播报记录 -->
          <div class="rounded-lg p-4 overflow-hidden" :style="{
            backgroundColor: 'var(--color-surface)',
            border: '1px solid var(--color-border)'
          }">
            <div class="flex items-center justify-between mb-3">
              <h4 class="text-white font-medium flex items-center">
                <History class="w-4 h-4 mr-2 text-purple-400" />
                {{ ts('播报记录') }}
              </h4>
              <span class="text-xs text-purple-400 bg-purple-400/20 px-2 py-1 rounded">
                {{ broadcastHistory.length }}{{ ts('条') }}
              </span>
            </div>
            <div class="space-y-2 max-h-32 overflow-y-auto custom-scrollbar">
              <div v-for="record in broadcastHistory.slice(0, 5)" :key="record.id"
                class="flex items-center justify-between p-2 rounded bg-white/5 hover:bg-white/10 transition-colors text-xs">
                <div class="flex items-center space-x-2 flex-1 min-w-0">
                  <component :is="getRecordIcon(record.type)" class="w-3 h-3 text-purple-400 flex-shrink-0" />
                  <span class="text-white truncate">{{ record.title || record.message.substring(0, 20) }}...</span>
                </div>
                <span class="text-gray-500 ml-2 flex-shrink-0">{{ formatTime(record.timestamp) }}</span>
              </div>

              <div v-if="broadcastHistory.length === 0" class="text-center text-white/50 text-sm py-4">
                <History class="w-6 h-6 mx-auto mb-1 opacity-50" />
                <p>{{ ts('暂无播报记录') }}</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 播报设置模态框 -->
    <div v-if="showBroadcastSettings" class="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4"
      @click="showBroadcastSettings = false">
      <div class="bg-gray-900 rounded-xl p-6 w-full max-w-md border border-electric-500/30" @click.stop>
        <div class="flex items-center justify-between mb-4">
          <h3 class="text-lg font-semibold text-white">{{ ts('数字人播报设置') }}</h3>
          <button @click="showBroadcastSettings = false" class="text-white/70 hover:text-white">
            <X class="w-5 h-5" />
          </button>
        </div>

        <div class="space-y-4">
          <!-- 播报速度 -->
          <div>
            <label class="block text-sm font-medium text-white mb-2">{{ ts('播报速度') }}</label>
            <select v-model="broadcastSettings.speed"
              class="w-full bg-white/10 border border-white/20 rounded-lg px-3 py-2 text-white">
              <option value="slow">{{ ts('慢速') }}</option>
              <option value="normal">{{ ts('正常') }}</option>
              <option value="fast">{{ ts('快速') }}</option>
            </select>
          </div>

          <!-- 播报类型 -->
          <div>
            <label class="block text-sm font-medium text-white mb-2">{{ ts('播报类型') }}</label>
            <div class="space-y-2">
              <label class="flex items-center space-x-2">
                <input type="checkbox" v-model="broadcastSettings.enableUrgent" class="rounded">
                <span class="text-white text-sm">{{ ts('紧急政策自动播报') }}</span>
              </label>
              <label class="flex items-center space-x-2">
                <input type="checkbox" v-model="broadcastSettings.enableDaily" class="rounded">
                <span class="text-white text-sm">{{ ts('每日摘要播报') }}</span>
              </label>
              <label class="flex items-center space-x-2">
                <input type="checkbox" v-model="broadcastSettings.enableCustom" class="rounded">
                <span class="text-white text-sm">{{ ts('定制政策播报') }}</span>
              </label>
            </div>
          </div>

          <!-- 播报音量 -->
          <div>
            <label class="block text-sm font-medium text-white mb-2">{{ ts('播报音量') }}</label>
            <input type="range" v-model="broadcastSettings.volume" min="0" max="100" class="w-full" />
            <div class="flex justify-between text-xs text-gray-400 mt-1">
              <span>0%</span>
              <span>{{ broadcastSettings.volume }}%</span>
              <span>100%</span>
            </div>
          </div>

          <div class="flex space-x-3 pt-4">
            <button @click="saveBroadcastSettings"
              class="flex-1 px-4 py-2 bg-electric-500 text-white rounded-lg hover:bg-electric-600 transition-colors">
              {{ ts('保存设置') }}
            </button>
            <button @click="resetBroadcastSettings"
              class="px-4 py-2 bg-gray-700 text-white rounded-lg hover:bg-gray-600 transition-colors">
              {{ ts('重置') }}
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, onUnmounted, watch } from 'vue'
import {
  Bot, Volume2, Radio, Settings, Target, Building, History, RefreshCw,
  Play, Pause, Square, X, Activity, Mic, Zap, FileText
} from 'lucide-vue-next'
import { useTranslation } from '../composables/useTranslation.js'
import intelligentAgent from '../services/intelligentAgent.js'

export default {
  name: 'DigitalHuman',
  components: {
    Bot, Volume2, Radio, Settings, Target, Building, History, RefreshCw,
    Play, Pause, Square, X, Activity, Mic, Zap, FileText
  },

  emits: ['broadcast-complete', 'policy-announce', 'settings-updated'],

  setup(props, { emit }) {
    const { ts } = useTranslation()

    // 基础状态
    const isAnnouncing = ref(false)
    const isSpeaking = ref(false)
    const isPaused = ref(false)
    const isTyping = ref(false)
    const agentActive = ref(true)
    const showBroadcastSettings = ref(false)

    // 播报相关
    const currentAnnouncement = ref(null)
    const displayedText = ref('')
    const announcementProgress = ref(0)
    const announcementQueue = ref([])

    // 数据列表
    const todayHighlights = ref([])
    const customPolicies = ref([])
    const broadcastHistory = ref([])

    // 视频控制相关
    const digitalHumanVideo = ref(null)

    // 视频控制方法
    const controlVideoPlayback = (shouldPlay) => {
      if (digitalHumanVideo.value) {
        try {
          if (shouldPlay) {
            digitalHumanVideo.value.play()
          } else {
            digitalHumanVideo.value.pause()
          }
        } catch (error) {
          console.warn('视频控制失败:', error)
        }
      }
    }

    // 播报设置
    const broadcastSettings = reactive({
      speed: 'normal',
      volume: 80,
      enableUrgent: true,
      enableDaily: true,
      enableCustom: true,
      autoplay: true
    })

    // 定时器
    let typewriterTimer = null
    let progressTimer = null
    let announcementTimer = null

    // 计算属性
    const currentStatus = computed(() => {
      if (isAnnouncing.value) return ts('播报中')
      if (isSpeaking.value) return ts('对话中')
      if (agentActive.value) return ts('在线待命')
      return ts('离线')
    })

    const currentStatusText = computed(() => {
      if (isAnnouncing.value) return ts('正在播报')
      if (agentActive.value) return ts('智能代理在线')
      return ts('代理离线')
    })

    const avatarBorderClass = computed(() => {
      if (isAnnouncing.value) return 'border-red-500/60 shadow-red-500/20 shadow-lg'
      if (isSpeaking.value) return 'border-yellow-500/60 shadow-yellow-500/20 shadow-lg'
      return 'border-electric-500/30 shadow-electric-500/10 shadow-lg'
    })

    const audioVisualizerClass = computed(() => {
      if (isAnnouncing.value) return 'bg-red-400 animate-pulse'
      if (isSpeaking.value) return 'bg-yellow-400 animate-pulse'
      return 'bg-electric-500'
    })

    // 方法
    const startTypewriterEffect = (text, callback) => {
      displayedText.value = ''
      isTyping.value = true
      let index = 0

      const typeSpeed = broadcastSettings.speed === 'fast' ? 50 :
        broadcastSettings.speed === 'slow' ? 150 : 100

      typewriterTimer = setInterval(() => {
        if (index < text.length) {
          displayedText.value += text[index]
          index++
        } else {
          isTyping.value = false
          clearInterval(typewriterTimer)
          if (callback) callback()
        }
      }, typeSpeed)
    }

    const startAnnouncementProgress = (duration) => {
      announcementProgress.value = 0
      const interval = 100 // 100ms更新一次
      const increment = (100 / duration) * interval

      progressTimer = setInterval(() => {
        if (!isPaused.value) {
          announcementProgress.value += increment
          if (announcementProgress.value >= 100) {
            clearInterval(progressTimer)
            completeCurrentAnnouncement()
          }
        }
      }, interval)
    }

    const startAnnouncement = (announcement) => {
      if (isAnnouncing.value) {
        // 如果正在播报，添加到队列
        announcementQueue.value.push(announcement)
        return
      }

      currentAnnouncement.value = announcement
      isAnnouncing.value = true
      isPaused.value = false

      // 控制视频播放
      controlVideoPlayback(true)

      // 开始打字机效果显示文本
      startTypewriterEffect(announcement.message, () => {
        // 文本显示完成后开始播报进度
        startAnnouncementProgress(announcement.duration)
      })

      // 添加到播报记录
      broadcastHistory.value.unshift({
        id: announcement.id,
        title: announcement.title || announcement.type,
        message: announcement.message,
        type: announcement.type,
        urgency: announcement.urgency,
        timestamp: Date.now()
      })

      // 保持最多20条记录
      if (broadcastHistory.value.length > 20) {
        broadcastHistory.value = broadcastHistory.value.slice(0, 20)
      }

      console.log('🎙️ 开始数字人播报:', announcement.message)
    }

    const completeCurrentAnnouncement = () => {
      if (currentAnnouncement.value) {
        const completed = currentAnnouncement.value

        // 发送播报完成事件
        emit('broadcast-complete', completed)

        // 清理当前播报
        currentAnnouncement.value = null
        isAnnouncing.value = false
        displayedText.value = ''
        announcementProgress.value = 0

        // 视频回到正常播放状态
        controlVideoPlayback(true)

        // 清理定时器
        if (typewriterTimer) clearInterval(typewriterTimer)
        if (progressTimer) clearInterval(progressTimer)

        console.log('✅ 播报完成:', completed.message)

        // 处理队列中的下一个播报
        if (announcementQueue.value.length > 0) {
          const nextAnnouncement = announcementQueue.value.shift()
          setTimeout(() => {
            startAnnouncement(nextAnnouncement)
          }, 1000) // 1秒间隔
        }
      }
    }

    const pauseOrResumeAnnouncement = () => {
      isPaused.value = !isPaused.value
      controlVideoPlayback(!isPaused.value)
    }

    const stopCurrentAnnouncement = () => {
      if (currentAnnouncement.value) {
        completeCurrentAnnouncement()
      }

      // 清空队列
      announcementQueue.value = []

      // 控制视频回到正常播放状态
      controlVideoPlayback(true)
    }

    const triggerManualBroadcast = () => {
      const message = generateManualBroadcastMessage()
      const announcement = {
        id: 'manual_' + Date.now(),
        message: message,
        type: 'manual_broadcast',
        urgency: 'normal',
        duration: 8000,
        timestamp: Date.now()
      }

      startAnnouncement(announcement)
    }

    const generateManualBroadcastMessage = () => {
      const templates = [
        `当前系统运行正常，已为您推荐${customPolicies.value.length}项定制政策，今日重点关注${todayHighlights.value.length}项推送。`,
        `智能代理系统活跃中，实时监控政策动态。目前有${todayHighlights.value.length}项重点推送等待您的关注。`,
        `系统状态良好，政策匹配引擎正常运行。已为您的企业特征匹配${customPolicies.value.length}项相关政策。`
      ]

      return templates[Math.floor(Math.random() * templates.length)]
    }

    const announceHighlight = (highlight) => {
      const message = generateHighlightMessage(highlight)
      const announcement = {
        id: 'highlight_' + Date.now(),
        message: message,
        type: 'highlight_broadcast',
        urgency: highlight.urgency,
        duration: calculateMessageDuration(message),
        timestamp: Date.now(),
        data: highlight
      }

      startAnnouncement(announcement)
      emit('policy-announce', highlight)
    }

    const generateHighlightMessage = (highlight) => {
      return `重点推送：${highlight.title}。${highlight.summary}。匹配度${Math.round((highlight.matchScore || 0.8) * 100)}%，建议重点关注。`
    }

    const announcePolicyDetails = (policy) => {
      const message = generatePolicyMessage(policy)
      const announcement = {
        id: 'policy_' + Date.now(),
        message: message,
        type: 'policy_detail',
        urgency: policy.urgency || 'normal',
        duration: calculateMessageDuration(message),
        timestamp: Date.now(),
        data: policy
      }

      startAnnouncement(announcement)
      emit('policy-announce', policy)
    }

    const generatePolicyMessage = (policy) => {
      return `政策详情：${policy.title}。${policy.description}。预期收益：${policy.benefit}。匹配度：${Math.round((policy.matchScore || 0.8) * 100)}%。建议详细了解申请条件和流程。`
    }

    const calculateMessageDuration = (message) => {
      const baseTime = 3000 // 基础3秒
      const charTime = message.length * 100 // 每字符100ms
      const speedMultiplier = broadcastSettings.speed === 'fast' ? 0.8 :
        broadcastSettings.speed === 'slow' ? 1.2 : 1

      return Math.round((baseTime + charTime) * speedMultiplier)
    }

    const refreshHighlights = async () => {
      console.log('🔄 刷新今日重点推送...')

      try {
        // 从智能代理获取推荐
        const recommendations = await intelligentAgent.generateCustomizedRecommendations()

        // 筛选高优先级的作为重点推送
        todayHighlights.value = recommendations
          .filter(policy => policy.urgency === 'high' || (policy.matchScore && policy.matchScore > 0.8))
          .slice(0, 10)
          .map(policy => ({
            id: policy.id,
            title: policy.title,
            summary: policy.description || policy.summary,
            urgency: policy.urgency || 'medium',
            matchScore: policy.matchScore,
            timestamp: Date.now(),
            type: policy.type,
            data: policy
          }))

        console.log(`✅ 刷新完成，获得${todayHighlights.value.length}项重点推送`)
      } catch (error) {
        console.error('❌ 刷新推送失败:', error)
      }
    }

    const refreshCustomPolicies = async () => {
      console.log('🔄 刷新企业定制政策...')

      try {
        const recommendations = await intelligentAgent.generateCustomizedRecommendations()

        customPolicies.value = recommendations
          .slice(0, 15)
          .map(policy => ({
            ...policy,
            timestamp: Date.now()
          }))

        console.log(`✅ 刷新完成，获得${customPolicies.value.length}项定制政策`)
      } catch (error) {
        console.error('❌ 刷新政策失败:', error)
      }
    }

    const openBroadcastSettings = () => {
      showBroadcastSettings.value = true
    }

    const saveBroadcastSettings = () => {
      // 保存设置到本地存储
      localStorage.setItem('digital_human_broadcast_settings', JSON.stringify(broadcastSettings))

      showBroadcastSettings.value = false
      emit('settings-updated', broadcastSettings)

      console.log('💾 播报设置已保存')
    }

    const resetBroadcastSettings = () => {
      Object.assign(broadcastSettings, {
        speed: 'normal',
        volume: 80,
        enableUrgent: true,
        enableDaily: true,
        enableCustom: true,
        autoplay: true
      })
    }

    const loadBroadcastSettings = () => {
      const saved = localStorage.getItem('digital_human_broadcast_settings')
      if (saved) {
        Object.assign(broadcastSettings, JSON.parse(saved))
      }
    }

    // 辅助方法
    const getUrgencyText = (urgency) => {
      const map = {
        'high': ts('紧急'),
        'medium': ts('重要'),
        'low': ts('一般'),
        'normal': ts('普通')
      }
      return map[urgency] || ts('普通')
    }

    const getUrgencyBadgeClass = (urgency) => {
      const map = {
        'high': 'bg-red-500/20 text-red-400',
        'medium': 'bg-yellow-500/20 text-yellow-400',
        'low': 'bg-green-500/20 text-green-400',
        'normal': 'bg-blue-500/20 text-blue-400'
      }
      return map[urgency] || 'bg-gray-500/20 text-gray-400'
    }

    const getHighlightBorderClass = (urgency) => {
      const map = {
        'high': 'border-red-500',
        'medium': 'border-yellow-500',
        'low': 'border-green-500',
        'normal': 'border-blue-500'
      }
      return map[urgency] || 'border-gray-500'
    }

    const getRecordIcon = (type) => {
      const map = {
        'manual_broadcast': Radio,
        'highlight_broadcast': Target,
        'policy_detail': FileText,
        'urgent_policy': Zap,
        'daily_digest': Activity
      }
      return map[type] || Radio
    }

    const formatTime = (timestamp) => {
      return new Date(timestamp).toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
      })
    }

    const formatDuration = (duration) => {
      const seconds = Math.ceil(duration / 1000)
      return `${seconds}秒`
    }

    // 智能代理事件处理
    const handleAgentAnnouncement = (announcement) => {
      if (broadcastSettings.enableUrgent && announcement.urgency === 'high') {
        startAnnouncement(announcement)
      } else if (broadcastSettings.enableDaily && announcement.type === 'daily_digest') {
        startAnnouncement(announcement)
      } else if (broadcastSettings.enableCustom && announcement.type === 'policy_update') {
        startAnnouncement(announcement)
      }
    }

    // 生命周期
    onMounted(async () => {
      console.log('🤖 数字人组件初始化...')

      // 加载设置
      loadBroadcastSettings()

      // 监听智能代理事件
      intelligentAgent.addEventListener('digitalHumanAnnouncement', handleAgentAnnouncement)

      // 初始化数据
      await refreshHighlights()
      await refreshCustomPolicies()

      // 检查代理状态
      agentActive.value = intelligentAgent.isActive

      console.log('✅ 数字人组件初始化完成')
    })

    onUnmounted(() => {
      // 清理定时器
      if (typewriterTimer) clearInterval(typewriterTimer)
      if (progressTimer) clearInterval(progressTimer)
      if (announcementTimer) clearInterval(announcementTimer)

      // 移除事件监听
      intelligentAgent.removeEventListener('digitalHumanAnnouncement', handleAgentAnnouncement)

      console.log('🔄 数字人组件已清理')
    })

    // 监听代理状态变化
    watch(() => intelligentAgent.isActive, (newValue) => {
      agentActive.value = newValue
    })

    return {
      // 状态
      isAnnouncing,
      isSpeaking,
      isPaused,
      isTyping,
      agentActive,
      showBroadcastSettings,

      // 播报相关
      currentAnnouncement,
      displayedText,
      announcementProgress,

      // 数据
      todayHighlights,
      customPolicies,
      broadcastHistory,

      // 视频控制
      digitalHumanVideo,

      // 设置
      broadcastSettings,

      // 计算属性
      currentStatus,
      currentStatusText,
      avatarBorderClass,
      audioVisualizerClass,

      // 方法
      triggerManualBroadcast,
      pauseOrResumeAnnouncement,
      stopCurrentAnnouncement,
      announceHighlight,
      announcePolicyDetails,
      refreshHighlights,
      refreshCustomPolicies,
      openBroadcastSettings,
      saveBroadcastSettings,
      resetBroadcastSettings,

      // 辅助方法
      getUrgencyText,
      getUrgencyBadgeClass,
      getHighlightBorderClass,
      getRecordIcon,
      formatTime,
      formatDuration,

      // 翻译
      ts
    }
  }
}
</script>

<style scoped>
.custom-scrollbar {
  scrollbar-width: thin;
  scrollbar-color: rgba(0, 245, 255, 0.3) transparent;
}

.custom-scrollbar::-webkit-scrollbar {
  width: 4px;
}

.custom-scrollbar::-webkit-scrollbar-track {
  background: transparent;
}

.custom-scrollbar::-webkit-scrollbar-thumb {
  background-color: rgba(0, 245, 255, 0.3);
  border-radius: 2px;
}

.custom-scrollbar::-webkit-scrollbar-thumb:hover {
  background-color: rgba(0, 245, 255, 0.5);
}

.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.typewriter-text {
  display: inline-block;
}

.animation-delay-200 {
  animation-delay: 0.2s;
}

.animation-delay-400 {
  animation-delay: 0.4s;
}

@keyframes glow {

  0%,
  100% {
    text-shadow: 0 0 5px rgba(0, 245, 255, 0.5);
  }

  50% {
    text-shadow: 0 0 20px rgba(0, 245, 255, 0.8);
  }
}

.animate-glow {
  animation: glow 2s ease-in-out infinite;
}
</style>